package com.fantasychong.myandroidapplication.webview;

import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.fantasychong.myandroidapplication.R;

/**
 * webview界面
 * Created by Fantasychong
 * Date: 2023/1/29
 * 核心是webview的内存泄漏优化：
 * 1.动态加载webview
 * 2.Manifest里webviewActivity开启个新进程
 * 3.onDestroy里移除webview并且移除进程
 */
public class WebViewActivity extends AppCompatActivity implements View.OnClickListener {

    private WebView wb;
    private Button backBtn;
    private Button nextBtn;
    private Button backOrNextBtn;
    private Button reloadBtn;
    private Button clearBtn;
    private LinearLayout layout;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
        initViews(); //配置组件
    }

    /**
     * 配置组件
     */
    private void initViews() {
        layout = findViewById(R.id.webview_layout);
        backBtn = findViewById(R.id.webview_backBtn);
        nextBtn = findViewById(R.id.webview_nextBtn);
        backOrNextBtn = findViewById(R.id.webview_backOrNextBtn);
        reloadBtn = findViewById(R.id.webview_reloadBtn);
        clearBtn = findViewById(R.id.webview_clearBtn);
        backBtn.setOnClickListener(this);
        nextBtn.setOnClickListener(this);
        backOrNextBtn.setOnClickListener(this);
        reloadBtn.setOnClickListener(this);
        clearBtn.setOnClickListener(this);

        //动态添加webview
        wb = new WebView(this);
        layout.addView(wb);

        //如果闪烁就关闭硬件加速 暂没派上用场
        wb.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

        WebSettings setting = wb.getSettings();

        //开启JS交互
        setting.setJavaScriptEnabled(true);

        //开启自适应屏幕
        setting.setUseWideViewPort(true);
        setting.setLoadWithOverviewMode(true);

        //缩放相关配置 1和2同时开启才能缩放 3则是隐藏默认的缩放控件
        setting.setSupportZoom(true);
        setting.setBuiltInZoomControls(true);
        setting.setDisplayZoomControls(false);
//        setting.setTextZoom(200);

        setting.setDefaultFontSize(40);

        //优先使用缓存
        setting.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        //开启后部分功能可正常向本地写数据
        setting.setDomStorageEnabled(true);

        wb.loadUrl("https://www.baidu.com");
//        String body = "示例：这里有个img标签，地址是相对路径示例：这里有个img标签，地址是相对路径示例：这里有个img标签，地址是相对路径示例：这里有个img标签，地址是相对路径示例：这里有个img标签，地址是相对路径<img src='https://img2.baidu.com/it/u=1395980100,2999837177&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1675098000&t=3b30b22507b27de8fcbd4c158f9ff29a' />";
//
//        wb.loadDataWithBaseURL("http://www.jcodecraeer.com", body, "text/html", "utf-8", null);

        //只要设置了setWebViewClient 就不会跳转到浏览器
        wb.setWebViewClient(new WebViewClient() {

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //可以重新加工编辑url
//
                url = url.replace("baidu", "hao123");
                Log.d("fan_sss", url);

                wb.loadUrl(url);
                return true;
            }
        });

        //监听网页的加载进度
        wb.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                Log.d("fan_sss", newProgress + "");
                super.onProgressChanged(view, newProgress);
            }
        });

    }

    /**
     * 点击监听
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.webview_backBtn:
                wb.goBack(); //回退
                break;
            case R.id.webview_nextBtn:
                wb.goForward(); //前进
                break;
            case R.id.webview_backOrNextBtn:
                wb.goBackOrForward(-2);
                break;
            case R.id.webview_reloadBtn:
                wb.reload(); //重新加载
//                wb.stopLoading(); //停止加载
//                wb.setDownloadListener(new DownloadListener() {
//                    @Override
//                    public void onDownloadStart(String s, String s1, String s2, String s3, long l) {
//                        Uri uri = Uri.parse("https://img2.baidu.com/it/u=1395980100,2999837177&fm=253&fmt=auto&app=120&f=JPEG?w=1200&h=675");
//                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//                        startActivity(intent);
//                    }
//                });
                break;
            case R.id.webview_clearBtn:
                wb.clearCache(true);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("fan_sss", "onResume");
        wb.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("fan_sss", "onPause");
        wb.onPause();
    }

    @Override
    protected void onDestroy() {
        Log.d("fan_sss", "onDestroy");
        if (wb != null) {
            ((ViewGroup) wb.getParent()).removeView(wb);
            wb.destroy();
            wb = null;
        }
        System.exit(0);
        super.onDestroy();
    }

}
